<?php

if (php_sapi_name() != 'cli') {
    die('Please run in the cli');
}
header("content-type:text/html;charset=utf-8");
include_once 'E:\phpStudy\PHPTutorial\WWW\live_z\code\queue\queue.php';

set_time_limit(0);
// memory_limit  范围是PHP_INI_ALL
//ini_set('memory_limit', '512M');


$ip = "127.0.0.1";
$port = 20001;

//创建socket
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if (empty($socket)) {
    throw new \Exception('create socket fail');
}
//绑定IP和端口
if (socket_bind($socket, $ip, $port) == false) {
    throw new \Exception('socket bind port fail');
}
//监听端口
if (socket_listen($socket, 8) == false) {
    throw new \Exception('socket listen port fail');
}
$queue = new queue();
$data = [];
do {

    $accept_resource = socket_accept($socket);
    //分发任务
    $queue->distribution_task();

    if ($accept_resource !== false) {
        /* 读取客户端传过来的资源，并转化为字符串 */
        $string = socket_read($accept_resource, 1024);
        /* socket_read的作用就是读出socket_accept()的资源并把它转化为字符串 */


        if (!empty($string)) {
            $in_data = json_decode($string, true);
            if ($in_data['action'] == 'done') {
                //根据task_id 去删除队列信息
                
            } elseif ($in_data['action'] == 'add') {
                $data['is_distribute'] = 1;
                $data['is_deal'] = 1;
                $data['data'] = $string;
                $data['task_id'] = md5(microtime(true) . uniqid() . mt_rand(1000000, 9999999));
                $queue->push($data);
            }


            echo 'server receive is :' . $string . PHP_EOL;

            $list = $queue->get_queue();

            $return_client = json_encode($queue->get_queue_array());

            socket_write($accept_resource, $return_client, strlen($return_client));
        } else {
            throw new \Exception('receive data empty');
        }

        socket_close($accept_resource);
    } else {
        throw new \Exception('socket receive data fail');
    }
} while (true);
